package com.massyframework.beanskin.runtime.nativelib;

import java.time.LocalDate;
import java.time.Period;
import java.util.Collections;
import java.util.List;

import com.massyframework.beanskin.license.License;

/**
 * 许可工具类
 * @author huangkh
 *
 */
abstract class LicenseUtils {

	/**
	 * 生成许可签名的内容
	 * @param license {@link License}
	 * @return
	 */
	public static String genericContent(License license) {
		StringBuilder builder = new StringBuilder();
		builder.append("module=")
			.append(license.getGroupId())
			.append(":").append(license.getModuleId())
			.append(":").append(license.getVersionRange().toString())
			.append(";");
		builder.append("customerId=")
			.append(Long.toString(license.getCustomerId()))
			.append(";");
		
		if (license.getExpireDate() != null) {
			builder.append("expiredDate=")
				.append(license.getExpireDate().toString())
				.append(";");
		}
		
		List<String> names = license.getParameterNames();
		if (!names.isEmpty()) {
			builder.append("[");
			Collections.sort(names);
			int size = names.size();
			for (int i=0; i<size; i++) {
				String name = names.get(i);
				String value = license.getParameter(name);
				builder.append(name).append("=").append(value);
				if (i != size -1) {
					builder.append(";");
				}
			}
			builder.append("]");
		}
		
		return builder.toString();
	}
	
	/**
	 * 判断许可是否超期
	 * <p>
	 * 返回值为
	 * <ul>
	 * <li>-1</li>远未到期
	 * <li>0</li>近期到期(7天内)
	 * <li>-1</li>已到期
	 * </ul>
	 * @param License {@link License}
	 * @return {@link int}
	 */
	public static int isExpire(License license) {
		if (license == null) return 1;
		
		LocalDate expireDate = license.getExpireDate();
		if (expireDate == null) return -1;  //远未到期
		
		LocalDate current = LocalDate.now();
		Period next = Period.between(current, expireDate);
		int days = next.getDays();
		
		if (days > 7) return -1; //远未到期
		if (days < 0) return 1;  //超期
		
		return 0; //近期到期（7天内到期）
	}
}
